/**
 * @file interface.js
 * @description 封装 uni-app 接口
 */

function request() {
  return uni.request(...arguments)
}

function showToast() {
  return uni.showToast({
    icon: 'none',
    duration: 2000,
    ...(arguments[0] ? arguments[0] : {}),
  })
}

function setNavigationBarTitle() {
  uni.setNavigationBarTitle(...arguments)
}

function getSystemInfoSync() {
  return uni.getSystemInfoSync(...arguments)
}

function setStorageSync() {
  uni.setStorageSync(...arguments)
}

function getStorageSync() {
  return uni.getStorageSync(...arguments)
}

function navigateTo() {
  uni.navigateTo(...arguments)
}

function redirectTo() {
  uni.redirectTo(...arguments)
}

function navigateBack() {
  uni.navigateBack(...arguments)
}

function showModal() {
  uni.showModal(...arguments)
}

function showModalSync() {
  return new Promise(resolve => {
    uni.showModal({
      ...arguments[0],
      success(res) {
        if (res.confirm) {
          resolve(true)
          return
        } else if (res.cancel) {
          // 在安卓 App 上点击蒙层也是 res.confirm === false
          // 用 cancel 来判断是否主动点击取消按钮
          resolve(false)
          return
        }

        // 其他情况返回 null
        // null 和 false 都是假值，只需要判断是否确认的话无影响
        resolve(null)
      },
      fail() {
        resolve(false)
      },
    })
  })
}

function scanCode() {
  uni.scanCode(...arguments)
}

function scanCodeSync() {
  return new Promise(resolve => {
    uni.scanCode({
      ...arguments[0],
      success(res) {
        resolve(res)
      },
      fail() {
        resolve(undefined)
      },
    })
  })
}

function previewImage() {
  uni.previewImage(...arguments)
}

function showLoading() {
  uni.showLoading(...arguments)
}

function hideLoading() {
  uni.hideLoading(...arguments)
}

function showActionSheet() {
  uni.showActionSheet(...arguments)
}

function eventOn(event, callback = () => { }) {
  uni.$on(event, payload => callback(payload))
}

function eventEmit(event, payload) {
  uni.$emit(event, payload)
}

export default {
  request,
  showToast,
  setNavigationBarTitle,
  getSystemInfoSync,
  setStorageSync,
  getStorageSync,
  navigateTo,
  redirectTo,
  navigateBack,
  showModal,
  showModalSync,
  scanCode,
  scanCodeSync,
  previewImage,
  showLoading,
  hideLoading,
  showActionSheet,
  eventOn,
  eventEmit,
}
